#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:read_file.py
# author:张世航
# datetime:2024/11/12 22:30
# software: PyCharm
"""
练习:  读取文件里面的内容(包含中文), 进行打印输出显示;
         注意:  请设置文件的不同编码格式进行观察;  另外,文件内容中包含中文字符;
"""
# import module your need

import sys
import os

# 创建文件 utf8_file.txt
with open("utf8_file.txt", "w", encoding="utf-8") as file:
    file.write("Python 是一个非常好的语言。\n是的，的确非常好!!")

# 创建文件 gbk_file.txt
with open("gbk_file.txt", "w", encoding="gbk") as file:
    file.write("Python 是一个非常好的语言。\n是的，的确非常好!!")

# 打印当前工作目录
print("当前工作目录:", os.getcwd())

# 读取UTF-8编码的文件
with open("utf8_file.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

# 读取GBK编码的文件
with open("gbk_file.txt", "r", encoding="gbk") as file:
    content = file.read()
    print(content)

# 如果系统编码不是UTF-8，可以先读取再转换
with open("utf8_file.txt", "r", encoding=sys.getfilesystemencoding()) as file:
    content = file.read()
    if sys.getfilesystemencoding() != 'utf-8':
        content = content.encode(sys.getfilesystemencoding()).decode('utf-8')
    print(content)